import { createRouter, createWebHashHistory } from 'vue-router'

import Login from '@/views/Login.vue';
import Home from '@/views/Home.vue';
import UserManage from '@/views/UserManage.vue';
import QuestionManage from '@/views/QuestionManage.vue'; // 新增导入
import CommentManage from '@/views/CommentManage.vue'; // 新增导入
import TagManage from '@/views/TagManage.vue'; // 新增导入
import ImageManage from '@/views/ImageManage.vue'; // 新增导入
import Error from '@/views/Error.vue'; // 也需要显式引入
import request from "@/api/request";

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'Login',
        component: Login,
    },
    {
        path: '/home',
        name: 'Home',
        component: Home,
        redirect: '/userManage',
        children: [
            {
                path: '/userManage',
                name: 'UserManage',
                component: UserManage,
            },
            {
                path: '/questionManage',
                name: 'QuestionManage',
                component: QuestionManage,
            },
            {
                path: '/commentManage',
                name: 'CommentManage',
                component: CommentManage,
            },
            {
                path: '/tagManage',
                name: 'TagManage',
                component: TagManage,
            },
            {
                path: '/imageManage',
                name: 'ImageManage',
                component: ImageManage,
            },
        ]
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'Error',
        component: Error,
    },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach(async (to, from, next) => {
    if (to.name === "Login" || to.name === "Home") {
        next();
    } else {
        const res = await request.post('/api/user/check')
        if (res.data.data) {
            next();
        } else {
            localStorage.removeItem('token')
            next("/login");
        }
    }
})

export default router
